//
//  XHRSickBranchesController.m
//  快医
//
//  Created by 孙博 on 16/7/8.
//
// SickBranches 疾病细分界面

#import "XHRSickBranchesController.h"
#import "XHRSickBranchesModel.h"
#import <MJRefreshNormalHeader.h>
#import "NSString+pinyin.h"
#import <SVProgressHUD.h>

@interface XHRSickBranchesController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>

@property (nonatomic, strong)NSArray<XHRSickBranchesModel *> *sickList;

@property (nonatomic, weak)UITableView *table;

// 存储搜索结果
@property (nonatomic, strong)NSMutableArray *results;

// 存储输出内容
@property (nonatomic, strong)NSArray *tempArr;

// 没有搜索结果
@property (nonatomic, assign)BOOL noResults;

@end

@implementation XHRSickBranchesController

- (NSMutableArray *)results{
    if (nil == _results) {
        _results = [NSMutableArray array];
    }
    return _results;
}

- (NSArray *)tempArr{
    if (nil == _tempArr) {
        _tempArr = self.sickList;
    }else{
        _tempArr = self.results.copy;
    }
    return _tempArr;
}

- (void)setSickList:(NSArray<XHRSickBranchesModel *> *)sickList{
    
    _sickList = sickList;
    [self.table reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor orangeColor];
    
    // 网络拉取数据
    [XHRSickBranchesModel getSickBranchesListSuccess:^(NSArray<XHRSickBranchesModel *> *sickList) {
        self.sickList = sickList;
    } error:^{
        NSLog(@"获取疾病细分数据失败");
    }];
    
    // 设置界面
    [self setupUI];
    
    // table注册
    [self.table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"sickBranches"];
}

- (void)setupUI{
    
    // search
    UISearchBar *search = [[UISearchBar alloc]init];
    search.delegate = self;
    [self.view addSubview:search];
    
    [search makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(0);
        make.leading.equalTo(0);
        make.trailing.equalTo(0);
        make.height.equalTo(40);
    }];
    
    // table
    UITableView *table = [UITableView new];
    table.dataSource = self;
    table.delegate = self;
    self.table = table;
    [self.view addSubview:table];
    
    [table makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(search.bottom);
        make.bottom.left.right.equalTo(0);
    }];
    
    // MARK:   设置刷新
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self performSelector:@selector(headRefresh)withObject:nil afterDelay:2.0f];
    }];
    
    // 设置刷新状态
    [header setTitle:@"正在刷新" forState:MJRefreshStateRefreshing];
    [header setTitle:@"刷新完成" forState:MJRefreshStateIdle];
    [header setTitle:@"松开加载更多" forState:MJRefreshStatePulling];
    
    // 将header赋值给table
    table.mj_header = header;
    
}

- (void)headRefresh{
    [self.table.mj_header endRefreshing];
}

#pragma
#pragma mark -search的代理
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    return YES;
}

// 没用
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
//    NSLog(@"结束编辑");
    return YES;
}

// 很有用
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
//    NSLog(@"输入的关键字是---%@---%lu",searchText,(unsigned long)searchText.length);
    //需要事先情况存放搜索结果的数组
    [self.results removeAllObjects];
    
    if (searchText!=nil && searchText.length>0) {
        //遍历需要搜索的所有内容，其中self.sickList为存放总数据的数组
        for (XHRSickBranchesModel *model in self.sickList) {
            
            NSString *tempStr = model.ci3_name;
            
            //----------->把所有的搜索结果转成成拼音
            NSString *pinyin = [self transformToPinyin:tempStr];
//            NSLog(@"pinyin--%@",pinyin);
            
            if ([pinyin rangeOfString:searchText options:NSCaseInsensitiveSearch].length >0 ) {
                //把搜索结果存放self.results数组
                [self.results addObject:model];
            }
        }
        if (self.results.count == 0) {
            self.noResults = YES;
        }
        [self.table reloadData];
    }else{
        self.results = [NSMutableArray arrayWithArray:self.sickList];
        [self.table reloadData];
    }
    
}

//   MARK:  搜索 NO_USE
- (void)searchResultsWithKey:(NSString *)string{
    
    // 清空之前的搜索结果
    [self.results removeAllObjects];
    
    // key转小写字母
    NSString *key = string.lowercaseString;
    
    NSMutableArray *tempArr = [NSMutableArray array];
    // key不为空时,遍历
    if (key != nil && key.length > 0) {
        // 将模型数组中的内容 遍历
        for (XHRSickBranchesModel *model in self.sickList) {
            
            // 转为小写
            NSString *name = model.ci3_name.lowercaseString;
            // 拼音再转为小写
            NSString *pingyin = [model.ci3_name transformToPinyin];
            // 转为小写首字母
            NSString *firstLetter = [model.ci3_name transformToPinyinFirstLetter];
            
            // 比较
             NSRange rang1 = [name rangeOfString:key];
            if (rang1.length>0) {// 直接包含key中的汉字
                [tempArr addObject:model];
            }else{
                if ([firstLetter containsString:key]) {//首字母包含key
                    [tempArr addObject:model];
                    
                }else{  //ershou
                    
                    if ([firstLetter containsString:[key substringToIndex:1]]) {
                        
                        if ([pingyin containsString:key] ) {
                            [tempArr addObject:model];
                        }
                    }
                }
            }
        }
        
        self.results = tempArr.copy;
        [self.table reloadData];
    }else{
        self.results = [NSMutableArray arrayWithArray:self.sickList];
        [self.table reloadData];
    }
}


#pragma
#pragma mark -table代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.results.count == 0) {
        return self.sickList.count;
    }
    return self.results.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sickBranches" forIndexPath:indexPath];
    
    XHRSickBranchesModel *model = [XHRSickBranchesModel new];
    
    if (self.results.count == 0) {
    
        if (self.noResults) {
            // 创建遮罩进行提示
            [SVProgressHUD setMinimumDismissTimeInterval:1];
            [SVProgressHUD showInfoWithStatus:@"没有此类疾病"];
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        }
        model = self.sickList[indexPath.row];
    } else{
        model = self.results[indexPath.row];
    }
    
    cell.textLabel.text = model.ci3_name;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.view endEditing:YES];
    // 选中莫某一行的时候,逆传数据
    XHRSickBranchesModel *model = self.sickList[indexPath.row];
    if (self.backBlock) {
        self.backBlock(model.ci3_name);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

// MARK: 将字符串转为拼音等
- (NSString *)transformToPinyin:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    NSArray *pinyinArray = [str componentsSeparatedByString:@" "];
    NSMutableString *allString = [NSMutableString new];
    
    int count = 0;
    for (int  i = 0; i < pinyinArray.count; i++)
    {
        for(int i = 0; i < pinyinArray.count;i++)
        {
            if (i == count) {
                [allString appendString:@"#"];//区分第几个字母
            }
            [allString appendFormat:@"%@",pinyinArray[i]];
        }
        [allString appendString:@","];
        count ++;
    }
    
    NSMutableString *initialStr = [NSMutableString new];//拼音首字母
    
    for (NSString *s in pinyinArray)
    {
        if (s.length > 0)
        {
            [initialStr appendString:  [s substringToIndex:1]];
        }
    }
    
    [allString appendFormat:@"#%@",initialStr];
    [allString appendFormat:@",#%@",aString];
    
    return allString;
}

@end
